import pytest
from selenium import webdriver
import os
from dotenv import load_dotenv
import allure

load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '.env'))


@pytest.fixture(scope='function')
def driver(request):
    browser = os.getenv('BROWSER').lower()
    if browser == 'chrome':
        driver = webdriver.Chrome()
    elif browser == 'firefox':
        driver = webdriver.Firefox()
    elif browser == 'edge':
        driver = webdriver.Edge()
    else:
        raise ValueError(f"不支持的浏览器类型: {browser}")
    driver.maximize_window()
    driver.implicitly_wait(int(os.getenv('TIMEOUT', '10')))
    yield driver
    driver.quit()


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    Pytest钩子函数，在测试执行后生成报告
    当测试失败时自动截取浏览器屏幕截图并添加到Allure报告中
    """
    # 执行测试并获取结果
    outcome = yield
    rep = outcome.get_result()
    
    # 检查测试是否在调用阶段失败
    if rep.when == "call" and rep.failed:
        # 获取测试中使用的driver实例
        driver = item.funcargs.get('driver', None)
        if driver:
            try:
                # 获取屏幕截图并附加到Allure报告
                screenshot = driver.get_screenshot_as_png()
                allure.attach(screenshot, name="失败截图", attachment_type=allure.attachment_type.PNG)
            except Exception as e:
                # 如果截图过程出错，记录警告信息
                print(f"截图失败: {str(e)}")
